<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html
    PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<!-- /fasttmp/mkdist-qt-4.3.5-1211793125/qtopia-core-opensource-src-4.3.5/doc/src/examples/imageviewer.qdoc -->
<head>
  <title>Qt 4.3: Image Viewer Example</title>
  <link href="classic.css" rel="stylesheet" type="text/css" />
</head>
<body>
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr>
<td align="left" valign="top" width="32"><a href="http://www.trolltech.com/products/qt"><img src="images/qt-logo.png" align="left" width="32" height="32" border="0" /></a></td>
<td width="1">&nbsp;&nbsp;</td><td class="postheader" valign="center"><a href="index.html"><font color="#004faf">Home</font></a>&nbsp;&middot; <a href="classes.html"><font color="#004faf">All&nbsp;Classes</font></a>&nbsp;&middot; <a href="mainclasses.html"><font color="#004faf">Main&nbsp;Classes</font></a>&nbsp;&middot; <a href="groups.html"><font color="#004faf">Grouped&nbsp;Classes</font></a>&nbsp;&middot; <a href="modules.html"><font color="#004faf">Modules</font></a>&nbsp;&middot; <a href="functions.html"><font color="#004faf">Functions</font></a></td>
<td align="right" valign="top" width="230"><a href="http://www.trolltech.com"><img src="images/trolltech-logo.png" align="right" width="203" height="32" border="0" /></a></td></tr></table><h1 align="center">Image Viewer Example<br /><small></small></h1>
<p>Files:</p>
<ul>
<li><a href="widgets-imageviewer-imageviewer-cpp.html">widgets/imageviewer/imageviewer.cpp</a></li>
<li><a href="widgets-imageviewer-imageviewer-h.html">widgets/imageviewer/imageviewer.h</a></li>
<li><a href="widgets-imageviewer-main-cpp.html">widgets/imageviewer/main.cpp</a></li>
</ul>
<p>The example shows how to combine <a href="qlabel.html">QLabel</a> and <a href="qscrollarea.html">QScrollArea</a> to display an image. <a href="qlabel.html">QLabel</a> is typically used for displaying text, but it can also display an image. <a href="qscrollarea.html">QScrollArea</a> provides a scrolling view around another widget. If the child widget exceeds the size of the frame, <a href="qscrollarea.html">QScrollArea</a> automatically provides scroll bars.</p>
<p>The example demonstrates how <a href="qlabel.html">QLabel</a>'s ability to scale its contents (<a href="qlabel.html#scaledContents-prop">QLabel::scaledContents</a>), and <a href="qscrollarea.html">QScrollArea</a>'s ability to automatically resize its contents (<a href="qscrollarea.html#widgetResizable-prop">QScrollArea::widgetResizable</a>), can be used to implement zooming and scaling features. In addition the example shows how to use <a href="qpainter.html">QPainter</a> to print an image.</p>
<p align="center"><img src="images/imageviewer-example.png" alt="Screenshot of the Image Viewer example" /></p><p>With the Image Viewer application, the users can view an image of their choice. The <b>File</b> menu gives the user the possibility to:</p>
<ul>
<li><b>Open..&#x2e;</b> - Open an image file</li>
<li><b>Print..&#x2e;</b> - Print an image</li>
<li><b>Exit</b> - Exit the application</li>
</ul>
<p>Once an image is loaded, the <b>View</b> menu allows the users to:</p>
<ul>
<li><b>Zoom In</b> - Scale the image up by 25%</li>
<li><b>Zoom Out</b> - Scale the image down by 25%</li>
<li><b>Normal Size</b> - Show the image at its original size</li>
<li><b>Fit to Window</b> - Stretch the image to occupy the entire window</li>
</ul>
<p>In addition the <b>Help</b> menu provides the users with information about the Image Viewer example in particular, and about Qt in general.</p>
<a name="imageviewer-class-definition"></a>
<h2>ImageViewer Class Definition</h2>
<pre> class ImageViewer : public QMainWindow
 {
     Q_OBJECT

 public:
     ImageViewer();

 private slots:
     void open();
     void print();
     void zoomIn();
     void zoomOut();
     void normalSize();
     void fitToWindow();
     void about();

 private:
     void createActions();
     void createMenus();
     void updateActions();
     void scaleImage(double factor);
     void adjustScrollBar(QScrollBar *scrollBar, double factor);

     QLabel *imageLabel;
     QScrollArea *scrollArea;
     double scaleFactor;

     QPrinter printer;

     QAction *openAct;
     QAction *printAct;
     QAction *exitAct;
     QAction *zoomInAct;
     QAction *zoomOutAct;
     QAction *normalSizeAct;
     QAction *fitToWindowAct;
     QAction *aboutAct;
     QAction *aboutQtAct;

     QMenu *fileMenu;
     QMenu *viewMenu;
     QMenu *helpMenu;
 };</pre>
<p>The <tt>ImageViewer</tt> class inherits from <a href="qmainwindow.html">QMainWindow</a>. We reimplement the constructor, and create several private slots to facilitate the menu entries. In addition we create four private functions.</p>
<p>We use <tt>createActions()</tt> and <tt>createMenus()</tt> when constructing the <tt>ImageViewer</tt> widget. We use the <tt>updateActions()</tt> function to update the menu entries when a new image is loaded, or when the <b>Fit to Window</b> option is toggled. The zoom slots use <tt>scaleImage()</tt> to perform the zooming. In turn, <tt>scaleImage()</tt> uses <tt>adjustScrollBar()</tt> to preserve the focal point after scaling an image.</p>
<a name="imageviewer-class-implementation"></a>
<h2>ImageViewer Class Implementation</h2>
<pre> ImageViewer::ImageViewer()
 {
     imageLabel = new QLabel;
     imageLabel-&gt;setBackgroundRole(QPalette::Base);
     imageLabel-&gt;setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored);
     imageLabel-&gt;setScaledContents(true);

     scrollArea = new QScrollArea;
     scrollArea-&gt;setBackgroundRole(QPalette::Dark);
     scrollArea-&gt;setWidget(imageLabel);
     setCentralWidget(scrollArea);

     createActions();
     createMenus();

     setWindowTitle(tr(&quot;Image Viewer&quot;));
     resize(500, 400);
 }</pre>
<p>In the constructor we first create the label and the scroll area.</p>
<p>We set <tt>imageLabel</tt>'s size policy to <a href="qsizepolicy.html#Policy-enum">ignored</a>, making the users able to scale the image to whatever size they want when the <b>Fit to Window</b> option is turned on. Otherwise, the default size polizy (<a href="qsizepolicy.html#Policy-enum">preferred</a>) will make scroll bars appear when the scroll area becomes smaller than the label's minimum size hint.</p>
<p>We ensure that the label will scale its contents to fill all available space, to enable the image to scale properly when zooming. If we omitted to set the <tt>imageLabel</tt>'s <a href="qlabel.html#scaledContents-prop">scaledContents</a> property, zooming in would enlarge the <a href="qlabel.html">QLabel</a>, but leave the pixmap at its original size, exposing the <a href="qlabel.html">QLabel</a>'s background.</p>
<p>We make <tt>imageLabel</tt> the scroll area's child widget, and we make <tt>scrollArea</tt> the central widget of the <a href="qmainwindow.html">QMainWindow</a>. At the end we create the associated actions and menus, and customize the <tt>ImageViewer</tt>'s appearance.</p>
<pre> void ImageViewer::open()
 {
     QString fileName = QFileDialog::getOpenFileName(this,
                                     tr(&quot;Open File&quot;), QDir::currentPath());
     if (!fileName.isEmpty()) {
         QImage image(fileName);
         if (image.isNull()) {
             QMessageBox::information(this, tr(&quot;Image Viewer&quot;),
                                      tr(&quot;Cannot load %1.&quot;).arg(fileName));
             return;
         }</pre>
<p>In the <tt>open()</tt> slot, we show a file dialog to the user. The easiest way to create a <a href="qfiledialog.html">QFileDialog</a> is to use the static convenience functions. <a href="qfiledialog.html#getOpenFileName">QFileDialog::getOpenFileName</a>() returns an existing file selected by the user. If the user presses <b>Cancel</b>, <a href="qfiledialog.html">QFileDialog</a> returns an empty string.</p>
<p>Unless the file name is a empty string, we check if the file's format is an image format by constructing a <a href="qimage.html">QImage</a> which tries to load the image from the file. If the constructor returns a null image, we use a <a href="qmessagebox.html">QMessageBox</a> to alert the user.</p>
<p>The <a href="qmessagebox.html">QMessageBox</a> class provides a modal dialog with a short message, an icon, and some buttons. As with <a href="qfiledialog.html">QFileDialog</a> the easiest way to create a <a href="qmessagebox.html">QMessageBox</a> is to use its static convenience functions. <a href="qmessagebox.html">QMessageBox</a> provides a range of different messages arranged along two axes: severity (question, information, warning and critical) and complexity (the number of necessary response buttons). In this particular example an information message with an <b>OK</b> button (the default) is sufficient, since the message is part of a normal operation.</p>
<pre>         imageLabel-&gt;setPixmap(QPixmap::fromImage(image));
         scaleFactor = 1.0;

         printAct-&gt;setEnabled(true);
         fitToWindowAct-&gt;setEnabled(true);
         updateActions();

         if (!fitToWindowAct-&gt;isChecked())
             imageLabel-&gt;adjustSize();
     }
 }</pre>
<p>If the format is supported, we display the image in <tt>imageLabel</tt> by setting the label's <a href="qlabel.html#pixmap-prop">pixmap</a>. Then we enable the <b>Print</b> and <b>Fit to Window</b> menu entries and update the rest of the view menu entries. The <b>Open</b> and <b>Exit</b> entries are enabled by default.</p>
<p>If the <b>Fit to Window</b> option is turned off, the <a href="qscrollarea.html#widgetResizable-prop">QScrollArea::widgetResizable</a> property is <tt>false</tt> and it is our responsibility (not <a href="qscrollarea.html">QScrollArea</a>'s) to give the <a href="qlabel.html">QLabel</a> a reasonable size based on its contents. We call {<a href="qwidget.html#adjustSize">QWidget::adjustSize</a>()}{adjustSize()} to achieve this, which is essentially the same as</p>
<pre> imageLabel-&gt;resize(imageLabel-&gt;pixmap()-&gt;size());</pre>
<p>In the <tt>print()</tt> slot, we first make sure that an image has been loaded into the application:</p>
<pre> void ImageViewer::print()
 {
     Q_ASSERT(imageLabel-&gt;pixmap());</pre>
<p>If the application is built in debug mode, the <tt>Q_ASSERT()</tt> macro will expand to</p>
<pre> if (!imageLabel-&gt;pixmap())
      qFatal(&quot;ASSERT: &quot;imageLabel-&gt;pixmap()&quot; in file ...&quot;);</pre>
<p>In release mode, the macro simply disappear. The mode can be set in the application's <tt>.pro</tt> file. One way to do so is to add an option to <b>qmake</b> when building the appliction:</p>
<pre> qmake &quot;CONFIG += debug&quot; foo.pro</pre>
<p>or</p>
<pre> qmake &quot;CONFIG += release&quot; foo.pro</pre>
<p>Another approach is to add this line directly to the <tt>.pro</tt> file.</p>
<pre>     QPrintDialog dialog(&amp;printer, this);
     if (dialog.exec()) {
         QPainter painter(&amp;printer);
         QRect rect = painter.viewport();
         QSize size = imageLabel-&gt;pixmap()-&gt;size();
         size.scale(rect.size(), Qt::KeepAspectRatio);
         painter.setViewport(rect.x(), rect.y(), size.width(), size.height());
         painter.setWindow(imageLabel-&gt;pixmap()-&gt;rect());
         painter.drawPixmap(0, 0, *imageLabel-&gt;pixmap());
     }
 }</pre>
<p>Then we present a print dialog allowing the user to choose a printer and to set a few options. We construct a painter with a <a href="qprinter.html">QPrinter</a> as the paint device. We set the painter's window and viewport in such a way that the image is as large as possible on the paper, but without altering its <a href="qt.html#AspectRatioMode-enum">aspect ratio</a>.</p>
<p>In the end we draw the pixmap at position (0, 0).</p>
<pre> void ImageViewer::zoomIn()
 {
     scaleImage(1.25);
 }

 void ImageViewer::zoomOut()
 {
     scaleImage(0.8);
 }</pre>
<p>We implement the zooming slots using the private <tt>scaleImage()</tt> function. We set the scaling factors to 1.25 and 0.8, respectively. These factor values ensure that a <b>Zoom In</b> action and a <b>Zoom Out</b> action will cancel each other (since 1.25 * 0.8 == 1), and in that way the normal image size can be restored using the zooming features.</p>
<p>The screenshots below show an image in its normal size, and the same image after zooming in:</p>
<p><table align="center" cellpadding="2" cellspacing="1" border="0">
<tr valign="top" class="odd"><td><img src="images/imageviewer-original_size.png" /></td><td><img src="images/imageviewer-zoom_in_1.png" /></td><td><img src="images/imageviewer-zoom_in_2.png" /></td></tr>
</table></p>
<pre> void ImageViewer::normalSize()
 {
     imageLabel-&gt;adjustSize();
     scaleFactor = 1.0;
 }</pre>
<p>When zooming, we use the <a href="qlabel.html">QLabel</a>'s ability to scale its contents. Such scaling doesn't change the actual size hint of the contents. And since the <a href="qwidget.html#adjustSize">adjustSize()</a> function use those size hint, the only thing we need to do to restore the normal size of the currently displayed image is to call <tt>adjustSize()</tt> and reset the scale factor to 1.0&#x2e;</p>
<pre> void ImageViewer::fitToWindow()
 {
     bool fitToWindow = fitToWindowAct-&gt;isChecked();
     scrollArea-&gt;setWidgetResizable(fitToWindow);
     if (!fitToWindow) {
         normalSize();
     }
     updateActions();
 }</pre>
<p>The <tt>fitToWindow()</tt> slot is called each time the user toggled the <b>Fit to Window</b> option. If the slot is called to turn on the option, we tell the scroll area to resize its child widget with the <a href="qscrollarea.html#widgetResizable-prop">QScrollArea::setWidgetResizable</a>() function. Then we disable the <b>Zoom In</b>, <b>Zoom Out</b> and <b>Normal Size</b> menu entries using the private <tt>updateActions()</tt> function.</p>
<p>If the <a href="qscrollarea.html#widgetResizable-prop">QScrollArea::widgetResizable</a> property is set to <tt>false</tt> (the default), the scroll area honors the size of its child widget. If this property is set to <tt>true</tt>, the scroll area will automatically resize the widget in order to avoid scroll bars where they can be avoided, or to take advantage of extra space. But the scroll area will honor the minimum size hint of its child widget independent of the widget resizable property. So in this example we set <tt>imageLabel</tt>'s size policy to <a href="qsizepolicy.html#Policy-enum">ignored</a> in the constructor, to avoid that scroll bars appear when the scroll area becomes smaller than the label's minimum size hint.</p>
<p>The screenshots below shows an image in its normal size, and the same image with the <b>Fit to window</b> option turned on. Enlarging the window will stretch the image further, as shown in the third screenshot.</p>
<p><table align="center" cellpadding="2" cellspacing="1" border="0">
<tr valign="top" class="odd"><td><img src="images/imageviewer-original_size.png" /></td><td><img src="images/imageviewer-fit_to_window_1.png" /></td><td><img src="images/imageviewer-fit_to_window_2.png" /></td></tr>
</table></p>
<p>If the slot is called to turn off the option, the {QScrollArea::setWidgetResizable} property is set to <tt>false</tt>. We also restore the image pixmap to its normal size by adjusting the label's size to its content. And in the end we update the view menu entries.</p>
<pre> void ImageViewer::about()
 {
     QMessageBox::about(this, tr(&quot;About Image Viewer&quot;),
             tr(&quot;&lt;p&gt;The &lt;b&gt;Image Viewer&lt;/b&gt; example shows how to combine QLabel &quot;
                &quot;and QScrollArea to display an image. QLabel is typically used &quot;
                &quot;for displaying a text, but it can also display an image. &quot;
                &quot;QScrollArea provides a scrolling view around another widget. &quot;
                &quot;If the child widget exceeds the size of the frame, QScrollArea &quot;
                &quot;automatically provides scroll bars. &lt;/p&gt;&lt;p&gt;The example &quot;
                &quot;demonstrates how QLabel's ability to scale its contents &quot;
                &quot;(QLabel::scaledContents), and QScrollArea's ability to &quot;
                &quot;automatically resize its contents &quot;
                &quot;(QScrollArea::widgetResizable), can be used to implement &quot;
                &quot;zooming and scaling features. &lt;/p&gt;&lt;p&gt;In addition the example &quot;
                &quot;shows how to use QPainter to print an image.&lt;/p&gt;&quot;));
 }</pre>
<p>We implement the <tt>about()</tt> slot to create a message box describing what the example is designed to show.</p>
<pre> void ImageViewer::createActions()
 {
     openAct = new QAction(tr(&quot;&amp;Open...&quot;), this);
     openAct-&gt;setShortcut(tr(&quot;Ctrl+O&quot;));
     connect(openAct, SIGNAL(triggered()), this, SLOT(open()));

     printAct = new QAction(tr(&quot;&amp;Print...&quot;), this);
     printAct-&gt;setShortcut(tr(&quot;Ctrl+P&quot;));
     printAct-&gt;setEnabled(false);
     connect(printAct, SIGNAL(triggered()), this, SLOT(print()));

     exitAct = new QAction(tr(&quot;E&amp;xit&quot;), this);
     exitAct-&gt;setShortcut(tr(&quot;Ctrl+Q&quot;));
     connect(exitAct, SIGNAL(triggered()), this, SLOT(close()));

     zoomInAct = new QAction(tr(&quot;Zoom &amp;In (25%)&quot;), this);
     zoomInAct-&gt;setShortcut(tr(&quot;Ctrl++&quot;));
     zoomInAct-&gt;setEnabled(false);
     connect(zoomInAct, SIGNAL(triggered()), this, SLOT(zoomIn()));

     zoomOutAct = new QAction(tr(&quot;Zoom &amp;Out (25%)&quot;), this);
     zoomOutAct-&gt;setShortcut(tr(&quot;Ctrl+-&quot;));
     zoomOutAct-&gt;setEnabled(false);
     connect(zoomOutAct, SIGNAL(triggered()), this, SLOT(zoomOut()));

     normalSizeAct = new QAction(tr(&quot;&amp;Normal Size&quot;), this);
     normalSizeAct-&gt;setShortcut(tr(&quot;Ctrl+S&quot;));
     normalSizeAct-&gt;setEnabled(false);
     connect(normalSizeAct, SIGNAL(triggered()), this, SLOT(normalSize()));

     fitToWindowAct = new QAction(tr(&quot;&amp;Fit to Window&quot;), this);
     fitToWindowAct-&gt;setEnabled(false);
     fitToWindowAct-&gt;setCheckable(true);
     fitToWindowAct-&gt;setShortcut(tr(&quot;Ctrl+F&quot;));
     connect(fitToWindowAct, SIGNAL(triggered()), this, SLOT(fitToWindow()));

     aboutAct = new QAction(tr(&quot;&amp;About&quot;), this);
     connect(aboutAct, SIGNAL(triggered()), this, SLOT(about()));

     aboutQtAct = new QAction(tr(&quot;About &amp;Qt&quot;), this);
     connect(aboutQtAct, SIGNAL(triggered()), qApp, SLOT(aboutQt()));
 }</pre>
<p>In the private <tt>createAction()</tt> function, we create the actions providing the application features.</p>
<p>We assign a short-cut key to each action and connect them to the appropiate slots. We only enable the <tt>openAct</tt> and <tt>exitAxt</tt> at the time of creation, the others are updated once an image has been loaded into the application. In addition we make the <tt>fitToWindowAct</tt> <a href="qaction.html#checkable-prop">checkable</a>.</p>
<pre> void ImageViewer::createMenus()
 {
     fileMenu = new QMenu(tr(&quot;&amp;File&quot;), this);
     fileMenu-&gt;addAction(openAct);
     fileMenu-&gt;addAction(printAct);
     fileMenu-&gt;addSeparator();
     fileMenu-&gt;addAction(exitAct);

     viewMenu = new QMenu(tr(&quot;&amp;View&quot;), this);
     viewMenu-&gt;addAction(zoomInAct);
     viewMenu-&gt;addAction(zoomOutAct);
     viewMenu-&gt;addAction(normalSizeAct);
     viewMenu-&gt;addSeparator();
     viewMenu-&gt;addAction(fitToWindowAct);

     helpMenu = new QMenu(tr(&quot;&amp;Help&quot;), this);
     helpMenu-&gt;addAction(aboutAct);
     helpMenu-&gt;addAction(aboutQtAct);

     menuBar()-&gt;addMenu(fileMenu);
     menuBar()-&gt;addMenu(viewMenu);
     menuBar()-&gt;addMenu(helpMenu);
 }</pre>
<p>In the private <tt>createMenu()</tt> function, we add the previously created actions to the <b>File</b>, <b>View</b> and <b>Help</b> menus.</p>
<p>The <a href="qmenu.html">QMenu</a> class provides a menu widget for use in menu bars, context menus, and other popup menus. The <a href="qmenubar.html">QMenuBar</a> class provides a horizontal menu bar that consists of a list of pull-down menu items. So at the end we put the menus in the <tt>ImageViewer</tt>'s menu bar which we retrieve with the <a href="qmainwindow.html#menuBar">QMainWindow::menuBar</a>() function.</p>
<pre> void ImageViewer::updateActions()
 {
     zoomInAct-&gt;setEnabled(!fitToWindowAct-&gt;isChecked());
     zoomOutAct-&gt;setEnabled(!fitToWindowAct-&gt;isChecked());
     normalSizeAct-&gt;setEnabled(!fitToWindowAct-&gt;isChecked());
 }</pre>
<p>The private <tt>updateActions()</tt> function enables or disables the <b>Zoom In</b>, <b>Zoom Out</b> and <b>Normal Size</b> menu entries depending on whether the <b>Fit to Window</b> option is turned on or off.</p>
<pre> void ImageViewer::scaleImage(double factor)
 {
     Q_ASSERT(imageLabel-&gt;pixmap());
     scaleFactor *= factor;
     imageLabel-&gt;resize(scaleFactor * imageLabel-&gt;pixmap()-&gt;size());

     adjustScrollBar(scrollArea-&gt;horizontalScrollBar(), factor);
     adjustScrollBar(scrollArea-&gt;verticalScrollBar(), factor);

     zoomInAct-&gt;setEnabled(scaleFactor &lt; 3.0);
     zoomOutAct-&gt;setEnabled(scaleFactor &gt; 0.333);
 }</pre>
<p>In <tt>scaleImage()</tt>, we use the <tt>factor</tt> parameter to calculate the new scaling factor for the displayed image, and resize <tt>imageLabel</tt>. Since we set the <a href="qlabel.html#scaledContents-prop">scaledContents</a> property to <tt>true</tt> in the constructor, the call to <a href="qwidget.html#size-prop">QWidget::resize</a>() will scale the image displayed in the label. We also adjust the scroll bars to preserve the focal point of the image.</p>
<p>At the end, if the scale factor is less than 33.3% or greater than 300%, we disable the respective menu entry to prevent the image pixmap from becoming too large, consuming too much resources in the window system.</p>
<pre> void ImageViewer::adjustScrollBar(QScrollBar *scrollBar, double factor)
 {
     scrollBar-&gt;setValue(int(factor * scrollBar-&gt;value()
                             + ((factor - 1) * scrollBar-&gt;pageStep()/2)));
 }</pre>
<p>Whenever we zoom in or out, we need to adjust the scroll bars in consequence. It would have been tempting to simply call</p>
<pre> scrollBar-&gt;setValue(int(factor * scrollBar-&gt;value()));</pre>
<p>but this would make the top-left corner the focal point, not the center. Therefore we need to take into account the scroll bar handle's size (the <a href="qabstractslider.html#pageStep-prop">page step</a>).</p>
<p /><address><hr /><div align="center">
<table width="100%" cellspacing="0" border="0"><tr class="address">
<td width="30%">Copyright &copy; 2008 <a href="trolltech.html">Trolltech</a></td>
<td width="40%" align="center"><a href="trademarks.html">Trademarks</a></td>
<td width="30%" align="right"><div align="right">Qt 4.3.5</div></td>
</tr></table></div></address></body>
</html>
